package com.cloud.tsp.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.utils.ExcelUtils;
import com.cloud.core.util.R;
import com.cloud.core.exception.MyException;
import com.cloud.api.domain.sys.SystemRoleDto;
import com.cloud.api.domain.tsp.*;
import com.cloud.api.constants.StrVo;
import com.cloud.mybatis.domain.TableDataInfo;
import com.cloud.tsp.mapper.VehicleInformationMapper;
import com.cloud.tsp.service.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author haohaibo
 * @since 2023-11-27
 */
@Service("vehicleInformationService")
public class VehicleInformationServiceImpl extends ServiceImpl<VehicleInformationMapper, VehicleInformation> implements IVehicleInformationService {

    @Resource
    private VehicleInformationMapper vehicleInformationMapper;
    @Resource
    private IVehicleTenantService vehicleTenantService;
    @Resource
    private IVehicleMessageDailyService vehicleMessageDailyService;
    @Resource
    private IVehicleOwnerService vehicleOwnerService;
    @Resource
    private IVehicleDeptService vehicleDeptService;
    @Resource
    private MessageSource messageSource;


    @Override
    public TableDataInfo<VehicleDto> selectVehicleList(QueryVehicle para) {
        Page<VehicleInformation> page =new Page<>();
        page.setCurrent(para.getPage());
        page.setSize(para.getPageSize());
        IPage<VehicleDto> data = vehicleInformationMapper.selectVehicleList(page, para);
        return TableDataInfo.build(data);
    }

    @Override
    public Long selectVehicleCount() {
        return vehicleInformationMapper.selectVehicleCount();
    }

    @Override
    public List<Integer> selectVehicleCountMonth() {
        return vehicleInformationMapper.selectVehicleCountMonth();
    }

    @Override
    public List<StrVo> selectVinScope() {

//        QueryVehicle permissions = getPermissions();
//        return vehicleInformationMapper.selectVinScope(permissions);
        return vehicleInformationMapper.selectVinScope(new QueryVehicle());
    }

    /*public QueryVehicle getPermissions(){
        QueryVehicle para = new QueryVehicle();
        para.setDataScope(LoginHelper.getDataScope());
        String userDept = LoginHelper.getUserLogin().getDeptId();
        if (para.getDataScope() == 5){
            R<SystemRoleDto> roleDetail = systemRoleOpenFeignService.getById(new StrVo(LoginHelper.getUserLogin().getRoleId()));
            String[] split = roleDetail.getData().getDeptIds().split(",");
            List<String> deptIds = new ArrayList<>(Arrays.asList(split));
            para.setDeptIds(deptIds);
        }else {
            List<String> list = new ArrayList<>();
            list.add(userDept);
            para.setDeptIds(list);
        }
        return para;
    }*/



    //原用于在线查询的redis全部车辆的缓存，现在改为数据库表关联查询
    public List<VehicleInformation> selectAllVehicleList() {
        List<VehicleInformation> vehicleInformations = vehicleInformationMapper.selectAllVehicleList1();
        return vehicleInformations;
    }

    @Override
    public VehicleDetail selectVehicleDetail(String vehicleId) {
        VehicleDetail vehicleDetail = new VehicleDetail();
        VehicleDto vehicleDto = vehicleInformationMapper.getById(vehicleId);
        vehicleDetail.setVehicleDto(vehicleDto);

        LambdaQueryWrapper<VehicleOwner> queryOwner = new LambdaQueryWrapper<>();
        queryOwner.eq(VehicleOwner::getVin,vehicleDto.getVin());
        VehicleOwner owner = vehicleOwnerService.getOne(queryOwner);
        vehicleDetail.setVehicleOwner(owner);

        LambdaQueryWrapper<VehicleTenant> queryTenant = new LambdaQueryWrapper<>();
        queryTenant.eq(VehicleTenant::getVin,vehicleDto.getVin());
        VehicleTenant tenant = vehicleTenantService.getOne(queryTenant);
        vehicleDetail.setVehicleTenant(tenant);

        return vehicleDetail;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertOrUpdate(VehicleDto para) {
        VehicleInformation vehicleInformation = new VehicleInformation();
        if (StringUtil.isBlank(para.getId())){
            para.setId(IdUtil.getSnowflakeNextIdStr());
            BeanUtils.copyProperties(para,vehicleInformation);
            vehicleInformationMapper.insert(vehicleInformation);

            LambdaQueryWrapper<VehicleDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VehicleDept::getVin,para.getVin());
            vehicleDeptService.remove(queryWrapper);
            VehicleDept vehicleDept = new VehicleDept();
            vehicleDept.setId(IdUtil.getSnowflakeNextIdStr());
            vehicleDept.setVin(para.getVin());
            vehicleDept.setDeptId(para.getDept());
            vehicleDeptService.save(vehicleDept);
        }else {
            vehicleInformation.setId(para.getId());
            vehicleInformation.setTboxNumber(para.getTboxNumber());
            vehicleInformation.setSimNumber(para.getSimNumber());
            vehicleInformation.setIccid(para.getIccid());
            vehicleInformation.setModel(para.getModel());
            vehicleInformationMapper.updateById(vehicleInformation);
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.name";
        String message = messageSource.getMessage(fileName, null, fileName, locale);
        Map<String, String> map = translateFields(locale);

        ExcelWriter excelWriter = ExcelUtil.getWriter(message+".xlsx");
        excelWriter.setColumnWidth(0, 20);
        excelWriter.setColumnWidth(1, 20);
        excelWriter.setColumnWidth(2, 20);
        excelWriter.setColumnWidth(3, 20);
        excelWriter.setColumnWidth(4, 20);
        StyleSet styleSet = excelWriter.getStyleSet();
        styleSet.setBackgroundColor(IndexedColors.GREY_25_PERCENT,false);
        excelWriter.writeRow(Arrays.asList(map.get("vin"),map.get("model"),map.get("tbox"),map.get("sim"),map.get("iccid")));
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename*=" + URLEncoder.encode(message+".xlsx", "UTF-8"));
        try {
            ServletOutputStream out=response.getOutputStream();
            excelWriter.flush(out,true);
            excelWriter.close();
            IoUtil.close(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void importVehicleList(String deptId, MultipartFile file) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        Map<String, String> map = translateFields(locale);

        List<String> excelHeaders = readExcelHeaders(file);
        List<String> header = Arrays.asList(map.get("vin"),map.get("model"),map.get("tbox"),map.get("sim"),map.get("iccid"));
        if (!header.equals(excelHeaders)) {
            throw new MyException("wds.exception.importHeaderError");
        }

        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        reader.addHeaderAlias(map.get("vin"),"vin")
                .addHeaderAlias( map.get("model"),"model")
                .addHeaderAlias(map.get("sim"),"simNumber")
                .addHeaderAlias(map.get("tbox"),"tboxNumber")
                .addHeaderAlias(map.get("iccid"),"iccid");
        List<VehicleInformation> vehicleInformation = reader.readAll(VehicleInformation.class);
        List<VehicleDept> list = new ArrayList<>();
        vehicleInformation.forEach(a -> {
            a.setId(IdUtil.getSnowflakeNextIdStr());
            VehicleDept vehicleDept = new VehicleDept();
            vehicleDept.setVin(a.getVin());
            vehicleDept.setDeptId(deptId);
            list.add(vehicleDept);
        });
        this.saveBatch(vehicleInformation);
        vehicleDeptService.saveBatch(list);
    }

    //获取表头
    static List<String> readExcelHeaders(MultipartFile file) throws IOException {
        List<String> headers = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
//        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        Row headerRow = sheet.getRow(0);

        for (Cell cell : headerRow) {
            CellType cellType = cell.getCellType();
            if (cellType== CellType.STRING){
                headers.add(cell.getStringCellValue());
            }
        }
        workbook.close();
        return headers;
    }


    @Override
    public void exportVehicleList(QueryVehicle para, HttpServletResponse response) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.name";
        String message = messageSource.getMessage(fileName, null, fileName, locale);
        Map<String, String> map = translateFields(locale);
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        List<VehicleDto> vehicleDtos = vehicleInformationMapper.selectAllVehicleList(para);
        bigWriter.setColumnWidth(0, 20);
        bigWriter.setColumnWidth(1, 20);
        bigWriter.setColumnWidth(2, 20);
        bigWriter.setColumnWidth(3, 20);
        bigWriter.setColumnWidth(4, 20);
        bigWriter.setColumnWidth(5, 30);
        bigWriter.setColumnWidth(6, 20);
        bigWriter.addHeaderAlias("vin", map.get("vin"));
        bigWriter.addHeaderAlias("model", map.get("model"));
        bigWriter.addHeaderAlias("tboxNumber", map.get("tbox"));
        bigWriter.addHeaderAlias("simNumber", map.get("sim"));
        bigWriter.addHeaderAlias("iccid", map.get("iccid"));
        bigWriter.addHeaderAlias("dept", map.get("organization"));
        bigWriter.addHeaderAlias("createTime", map.get("createTime"));
        bigWriter.setOnlyAlias(true);
        CellStyle headCellStyle = bigWriter.getHeadCellStyle();
        headCellStyle.setFillBackgroundColor((short) 22);
        bigWriter.write(vehicleDtos);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(message+".xlsx", "UTF8"));
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try {
            Workbook workbook = bigWriter.getWorkbook();
            ServletOutputStream out=response.getOutputStream();
            workbook.write(out);
            workbook.close();
            out.close();
            bigWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public Map<String, String> translateFields(Locale locale){
        Map<String,String> map = new HashMap<>();
        String vin = "table.field.vin";
        String model = "table.field.model";
        String tbox = "table.field.tbox";
        String sim = "table.field.sim";
        String iccid = "table.field.iccid";
        String organization = "table.field.organization";
        String createTime = "table.field.createTime";

        map.put("vin",messageSource.getMessage(vin, null, vin, locale));
        map.put("model",messageSource.getMessage(model, null, model, locale));
        map.put("tbox",messageSource.getMessage(tbox, null, tbox, locale));
        map.put("sim",messageSource.getMessage(sim, null, sim, locale));
        map.put("iccid",messageSource.getMessage(iccid, null, iccid, locale));
        map.put("organization",messageSource.getMessage(organization, null, organization, locale));
        map.put("createTime",messageSource.getMessage(createTime, null, createTime, locale));
        return map;
    }

}